import { Grade } from '../models/Grade.js';
import { ClassGrade } from '../models/ClassGrade.js';
import { Student } from '../models/Student.js';
import { CourseModel  } from '../models/Course.js';
import { Class } from '../models/Class.js';
import { upload } from '../middleware/upload.js';
import xlsx from 'xlsx';
import fs from 'fs';

const gradeModel = new Grade();
const classGradeModel = new ClassGrade();
const studentModel = new Student();
const courseModel = new CourseModel();
const classModel = new Class();

export class GradeController {
  // 下载成绩导入模板
  downloadTemplate(req, res) {
    try {
      console.log('开始生成成绩导入模板...');
      
      // 创建模板数据
      const templateData = [
        ['学号', '姓名', '班级', '课程代码', '课程名称', '平时成绩', '期中成绩', '期末成绩', '学期', '学年', '教学月度', '考试日期'],
        ['20240001', '张三', '计算机科学与技术1班', 'AI001', '企业级人工智能项目实训一', '85', '78', '82', '2023-2024-2', '2023-2024', '实训1', '2024-01-15'],
        ['20240002', '李四', '软件工程2班', 'AI002', '企业级人工智能项目实训二', '90', '85', '88', '2023-2024-2', '2023-2024', '实训2', '2024-01-15'],
        ['', '', '', 'PY001', 'Python程序设计', '', '', '', '2023-2024-2', '2023-2024', '', '']
      ];
      
      // 创建工作簿
      const wb = xlsx.utils.book_new();
      const ws = xlsx.utils.aoa_to_sheet(templateData);
      
      // 设置列宽
      const colWidths = [
        { wch: 15 }, { wch: 10 }, { wch: 20 }, { wch: 12 }, { wch: 25 },
        { wch: 10 }, { wch: 10 }, { wch: 10 }, { wch: 15 }, { wch: 10 }, { wch: 12 }, { wch: 12 }
      ];
      ws['!cols'] = colWidths;
      
      xlsx.utils.book_append_sheet(wb, ws, '成绩导入模板');
      
      // 生成Excel文件
      const buffer = xlsx.write(wb, { 
        type: 'buffer', 
        bookType: 'xlsx'
      });
      
      if (!buffer || buffer.length === 0) {
        throw new Error('生成的Excel文件为空');
      }
      
      console.log('Excel文件生成成功，大小:', buffer.length, 'bytes');
      
      const filename = 'grade_template.xlsx';
      const chineseFilename = '成绩导入模板.xlsx';
      
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      res.setHeader('Content-Disposition', `attachment; filename="${filename}"; filename*=UTF-8''${encodeURIComponent(chineseFilename)}`);
      res.setHeader('Content-Length', buffer.length);
      res.setHeader('Cache-Control', 'no-cache');
      
      res.send(buffer);
      
      console.log('模板文件发送成功');
      
    } catch (error) {
      console.error('生成模板失败:', error);
      res.status(500).json({ 
        success: false,
        error: '生成模板失败',
        details: error.message 
      });
    }
  }

  // 导入成绩数据
  async importGrades(req, res) {
    let tempFilePath = null;
    
    try {
      if (!req.file) {
        return res.status(400).json({ 
          success: false,
          error: '请选择要上传的文件' 
        });
      }

      tempFilePath = req.file.path;
      console.log('开始处理上传文件:', req.file.originalname, '路径:', tempFilePath);

      if (!fs.existsSync(tempFilePath)) {
        return res.status(400).json({ 
          success: false,
          error: '文件不存在或无法访问' 
        });
      }

      const stats = fs.statSync(tempFilePath);
      console.log('文件大小:', stats.size, 'bytes');

      if (stats.size === 0) {
        fs.unlinkSync(tempFilePath);
        return res.status(400).json({ 
          success: false,
          error: '文件内容为空' 
        });
      }

      // 读取Excel文件
      let workbook;
      try {
        workbook = xlsx.readFile(tempFilePath);
        console.log('Excel文件读取成功，工作表:', workbook.SheetNames);
      } catch (excelError) {
        console.error('读取Excel文件失败:', excelError);
        fs.unlinkSync(tempFilePath);
        return res.status(400).json({ 
          success: false,
          error: '无法读取Excel文件，请确保文件格式正确' 
        });
      }

      const sheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[sheetName];
      
      if (!worksheet) {
        fs.unlinkSync(tempFilePath);
        return res.status(400).json({ 
          success: false,
          error: 'Excel文件中没有找到工作表' 
        });
      }

      const data = xlsx.utils.sheet_to_json(worksheet, { 
        header: 1,
        defval: '',
        blankrows: false
      });
      
      console.log('解析到的数据行数:', data.length);

      if (data.length <= 1) {
        fs.unlinkSync(tempFilePath);
        return res.status(400).json({ 
          success: false,
          error: '文件内容为空或格式不正确，请确保有数据行' 
        });
      }

      const headers = data[0].map(h => h ? h.toString().trim() : '');
      console.log('文件表头:', headers);

      const expectedHeaders = {
        '学号': 'studentId',
        '姓名': 'studentName', 
        '班级': 'className',
        '课程代码': 'courseCode',
        '课程名称': 'courseName',
        '平时成绩': 'regularGrade',
        '期中成绩': 'midtermGrade',
        '期末成绩': 'finalGrade',
        '学期': 'semester',
        '学年': 'academicYear',
        '教学月度': 'teachingMonth',
        '考试日期': 'examDate'
      };

      const requiredHeaders = ['学号', '课程代码'];
      const missingHeaders = requiredHeaders.filter(header => !headers.includes(header));
      
      if (missingHeaders.length > 0) {
        fs.unlinkSync(tempFilePath);
        return res.status(400).json({ 
          success: false,
          error: `文件缺少必要的表头: ${missingHeaders.join(', ')}` 
        });
      }

      const headerMap = {};
      headers.forEach((header, index) => {
        if (expectedHeaders[header]) {
          headerMap[expectedHeaders[header]] = index;
        }
      });

      console.log('表头映射:', headerMap);

      const results = {
        total: 0,
        success: 0,
        failed: 0,
        errors: []
      };

      const grades = gradeModel.findAll();
      const students = studentModel.findAll();
      const courses = [
        {
          id: 1,
          name: "企业级人工智能项目实训一",
          code: "AI001",
          teacher: "曲凤才",
          teacherId: 2,
          credit: 4,
          hours: 64
        },
        {
          id: 2,
          name: "企业级人工智能项目实训二", 
          code: "AI002",
          teacher: "曲凤才",
          teacherId: 2,
          credit: 4,
          hours: 64
        },
        {
          id: 3,
          name: "Python程序设计",
          code: "PY001",
          teacher: "张老师",
          teacherId: 2,
          credit: 3,
          hours: 48
        }
      ];

      for (let i = 1; i < data.length; i++) {
        const row = data[i];
        if (!row || row.length === 0) continue;

        results.total++;

        try {
          const getValue = (field) => {
            const index = headerMap[field];
            return index !== undefined && row[index] !== undefined ? row[index] : '';
          };

          const studentId = getValue('studentId');
          const studentName = getValue('studentName');
          const className = getValue('className');
          const courseCode = getValue('courseCode');
          const courseName = getValue('courseName');
          const regularGrade = getValue('regularGrade');
          const midtermGrade = getValue('midtermGrade');
          const finalGrade = getValue('finalGrade');
          const semester = getValue('semester');
          const academicYear = getValue('academicYear');
          const teachingMonth = getValue('teachingMonth');
          const examDate = getValue('examDate');

          console.log(`处理第${i+1}行:`, { studentId, courseCode });

          if (!studentId || !studentId.toString().trim()) {
            results.failed++;
            results.errors.push(`第${i+1}行: 学号为必填字段`);
            continue;
          }

          if (!courseCode || !courseCode.toString().trim()) {
            results.failed++;
            results.errors.push(`第${i+1}行: 课程代码为必填字段`);
            continue;
          }

          const student = students.find(s => s.studentId === studentId.toString().trim());
          if (!student) {
            results.failed++;
            results.errors.push(`第${i+1}行: 学号 "${studentId}" 对应的学生不存在`);
            continue;
          }

          const course = courses.find(c => c.code === courseCode.toString().trim());
          if (!course) {
            results.failed++;
            results.errors.push(`第${i+1}行: 课程代码 "${courseCode}" 对应的课程不存在，可用课程: ${courses.map(c => c.code).join(', ')}`);
            continue;
          }

          // 计算总成绩和绩点
          const regular = regularGrade ? parseFloat(regularGrade) || 0 : 0;
          const midterm = midtermGrade ? parseFloat(midtermGrade) || 0 : 0;
          const final = finalGrade ? parseFloat(finalGrade) || 0 : 0;
          const totalGrade = gradeModel.calculateTotalGrade(regular, midterm, final);
          const gradePoint = gradeModel.calculateGradePoint(totalGrade);

          const newGrade = {
            studentId: student.id,
            studentName: studentName && studentName.toString().trim() ? studentName.toString().trim() : student.name,
            studentNumber: studentId.toString().trim(),
            courseId: course.id,
            courseCode: courseCode.toString().trim(),
            courseName: courseName && courseName.toString().trim() ? courseName.toString().trim() : course.name,
            className: className && className.toString().trim() ? className.toString().trim() : student.className,
            regularGrade: regular,
            midtermGrade: midterm,
            finalGrade: final,
            totalGrade: totalGrade,
            gradePoint: gradePoint,
            semester: semester && semester.toString().trim() ? semester.toString().trim() : '2023-2024-2',
            academicYear: academicYear && academicYear.toString().trim() ? academicYear.toString().trim() : '2023-2024',
            teachingMonth: teachingMonth && teachingMonth.toString().trim() ? teachingMonth.toString().trim() : '',
            examDate: examDate && examDate.toString().trim() ? examDate.toString().trim() : new Date().toISOString().split('T')[0],
            teacher: course.teacher || '待分配',
            credit: course.credit || 0,
            status: 'published'
          };

          gradeModel.create(newGrade);
          results.success++;
          console.log(`第${i+1}行导入成功`);

        } catch (error) {
          results.failed++;
          results.errors.push(`第${i+1}行: 数据处理失败 - ${error.message}`);
          console.error(`处理第${i+1}行时出错:`, error);
        }
      }

      if (tempFilePath && fs.existsSync(tempFilePath)) {
        fs.unlinkSync(tempFilePath);
      }

      res.json({
        success: true,
        message: `导入完成: 成功 ${results.success} 条，失败 ${results.failed} 条，总计 ${results.total} 条`,
        data: results
      });

    } catch (error) {
      console.error('导入失败:', error);
      
      if (tempFilePath && fs.existsSync(tempFilePath)) {
        fs.unlinkSync(tempFilePath);
      }
      
      res.status(500).json({ 
        success: false,
        error: `导入失败: ${error.message}`,
        details: error.stack
      });
    }
  }

  // 获取成绩列表
  async getGrades(req, res) {
    try {
      console.log('获取成绩列表，查询参数:', req.query);
      
      const grades = gradeModel.findAll();
      
      // 处理分页
      const page = parseInt(req.query.page) || 1;
      const pageSize = parseInt(req.query.pageSize) || 10;
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      
      // 应用搜索过滤
      let filteredGrades = [...grades];
      
      // 关键词搜索
      if (req.query.keyword) {
        const keyword = req.query.keyword.toLowerCase();
        filteredGrades = filteredGrades.filter(grade => 
          grade.studentName.toLowerCase().includes(keyword) ||
          grade.studentNumber.toLowerCase().includes(keyword) ||
          grade.courseName.toLowerCase().includes(keyword) ||
          grade.className.toLowerCase().includes(keyword) ||
          grade.teacher.toLowerCase().includes(keyword)
        );
      }
      
      // 字段精确搜索
      const searchFields = ['studentNumber', 'courseCode', 'className', 'semester', 'teacher'];
      searchFields.forEach(field => {
        if (req.query[field] && req.query[field].trim()) {
          const searchValue = req.query[field].toLowerCase();
          filteredGrades = filteredGrades.filter(grade => {
            const fieldValue = grade[field];
            return fieldValue && fieldValue.toString().toLowerCase().includes(searchValue);
          });
        }
      });
      
      // 分页
      const paginatedGrades = filteredGrades.slice(startIndex, endIndex);
      
      // 构建响应
      const response = {
        success: true,
        data: paginatedGrades,
        pagination: {
          current: page,
          pageSize: pageSize,
          total: filteredGrades.length,
          totalPages: Math.ceil(filteredGrades.length / pageSize)
        }
      };
      
      res.json(response);
    } catch (error) {
      console.error('获取成绩列表失败:', error);
      res.status(500).json({ 
        success: false,
        error: '获取失败' 
      });
    }
  }

  // 创建成绩记录
  async createGrade(req, res) {
    try {
      const gradeData = req.body;
      console.log('创建成绩记录:', gradeData);
      
      // 计算总成绩和绩点
      const regular = gradeData.regularGrade || 0;
      const midterm = gradeData.midtermGrade || 0;
      const final = gradeData.finalGrade || 0;
      const totalGrade = gradeModel.calculateTotalGrade(regular, midterm, final);
      const gradePoint = gradeModel.calculateGradePoint(totalGrade);
      
      const newGradeData = {
        ...gradeData,
        totalGrade: totalGrade,
        gradePoint: gradePoint,
        status: 'published'
      };
      
      const newGrade = gradeModel.create(newGradeData);
      
      if (newGrade) {
        res.status(201).json({
          success: true,
          data: newGrade
        });
      } else {
        res.status(500).json({ 
          success: false,
          error: '保存失败' 
        });
      }
    } catch (error) {
      console.error('创建成绩记录失败:', error);
      res.status(500).json({ 
        success: false,
        error: '创建失败' 
      });
    }
  }

  // 更新成绩记录
  async updateGrade(req, res) {
    try {
      const { id } = req.params;
      const gradeData = req.body;
      console.log('更新成绩记录:', id, gradeData);
      
      // 计算总成绩和绩点
      const regular = gradeData.regularGrade || 0;
      const midterm = gradeData.midtermGrade || 0;
      const final = gradeData.finalGrade || 0;
      const totalGrade = gradeModel.calculateTotalGrade(regular, midterm, final);
      const gradePoint = gradeModel.calculateGradePoint(totalGrade);
      
      const updateData = {
        ...gradeData,
        totalGrade: totalGrade,
        gradePoint: gradePoint
      };
      
      const updatedGrade = gradeModel.update(id, updateData);
      
      if (updatedGrade) {
        res.json({
          success: true,
          data: updatedGrade
        });
      } else {
        res.status(404).json({ 
          success: false,
          error: '成绩记录不存在' 
        });
      }
    } catch (error) {
      console.error('更新成绩记录失败:', error);
      res.status(500).json({ 
        success: false,
        error: '更新失败' 
      });
    }
  }

  // 删除成绩记录
  async deleteGrade(req, res) {
    try {
      const { id } = req.params;
      console.log('删除成绩记录:', id);
      
      const success = gradeModel.delete(id);
      
      if (success) {
        res.json({ 
          success: true,
          message: '删除成功' 
        });
      } else {
        res.status(404).json({ 
          success: false,
          error: '成绩记录不存在' 
        });
      }
    } catch (error) {
      console.error('删除成绩记录失败:', error);
      res.status(500).json({ 
        success: false,
        error: '删除失败' 
      });
    }
  }

  // 获取成绩统计
  async getGradeStats(req, res) {
    try {
      const grades = gradeModel.findAll();
      const students = studentModel.findAll();
      const courses = [
        { id: 1, name: "企业级人工智能项目实训一", code: "AI001" },
        { id: 2, name: "企业级人工智能项目实训二", code: "AI002" },
        { id: 3, name: "Python程序设计", code: "PY001" }
      ];
      
      const totalGrades = grades.length;
      const totalStudents = new Set(grades.map(g => g.studentId)).size;
      const totalCourses = new Set(grades.map(g => g.courseId)).size;
      
      // 按课程统计
      const courseStats = courses.map(course => {
        const courseGrades = grades.filter(g => g.courseId === course.id);
        const scores = courseGrades.map(g => g.totalGrade);
        const averageScore = scores.length > 0 ? scores.reduce((a, b) => a + b) / scores.length : 0;
        const maxScore = scores.length > 0 ? Math.max(...scores) : 0;
        const minScore = scores.length > 0 ? Math.min(...scores) : 0;
        const passCount = scores.filter(score => score >= 60).length;
        const passRate = scores.length > 0 ? (passCount / scores.length * 100).toFixed(1) : 0;
        
        return {
          courseName: course.name,
          courseCode: course.code,
          totalStudents: courseGrades.length,
          averageScore: parseFloat(averageScore.toFixed(1)),
          maxScore: maxScore,
          minScore: minScore,
          passRate: parseFloat(passRate)
        };
      });
      
      // 按班级统计
      const classStats = students.reduce((acc, student) => {
        const className = student.className;
        if (!className) return acc;
        
        if (!acc[className]) {
          acc[className] = {
            className: className,
            totalStudents: 0,
            totalGrades: 0,
            averageScore: 0
          };
        }
        
        const classGrades = grades.filter(g => g.studentId === student.id);
        acc[className].totalStudents++;
        acc[className].totalGrades += classGrades.length;
        
        if (classGrades.length > 0) {
          const classAverage = classGrades.reduce((sum, g) => sum + g.totalGrade, 0) / classGrades.length;
          acc[className].averageScore = parseFloat(classAverage.toFixed(1));
        }
        
        return acc;
      }, {});
      
      res.json({
        success: true,
        data: {
          totalGrades,
          totalStudents,
          totalCourses,
          courseStats,
          classStats: Object.values(classStats)
        }
      });
    } catch (error) {
      console.error('获取成绩统计失败:', error);
      res.status(500).json({ 
        success: false,
        error: '获取失败' 
      });
    }
  }

  // 获取学生个人成绩
  async getStudentGrades(req, res) {
    try {
      const { studentId } = req.params;
      console.log('获取学生个人成绩:', studentId);
      
      const student = studentModel.findByStudentId(studentId);
      if (!student) {
        return res.status(404).json({ 
          success: false,
          error: '学生不存在' 
        });
      }
      
      const grades = gradeModel.findByStudentId(student.id);
      
      // 计算平均分和总学分
      const totalCredits = grades.reduce((sum, grade) => sum + (grade.credit || 0), 0);
      const totalGradePoints = grades.reduce((sum, grade) => sum + (grade.gradePoint || 0) * (grade.credit || 0), 0);
      const gpa = totalCredits > 0 ? (totalGradePoints / totalCredits).toFixed(2) : 0;
      
      res.json({
        success: true,
        data: {
          student: {
            id: student.id,
            name: student.name,
            studentId: student.studentId,
            className: student.className
          },
          grades: grades,
          summary: {
            totalCourses: grades.length,
            totalCredits: totalCredits,
            gpa: parseFloat(gpa),
            averageScore: grades.length > 0 ? 
              (grades.reduce((sum, grade) => sum + grade.totalGrade, 0) / grades.length).toFixed(1) : 0
          }
        }
      });
    } catch (error) {
      console.error('获取学生个人成绩失败:', error);
      res.status(500).json({ 
        success: false,
        error: '获取失败' 
      });
    }
  }
}